# 屏幕大小650 550 素材大小38x38
from pickle import FALSE

import pygame
import tkinter as Tk

from Tools.scripts.objgraph import flat
from pygame.locals import *
from need.extend import fake_copy, init_pos, get_pos, get_total, is_same, show_pic, wash, \
	get_tip, wash_down, level_wash
import sqlite3
from itertools import cycle
import time
from need.tools import tool
from loading import pic, bg, button, top, good, nogood, order, success, over, sorry, false, restart, bg_sound, \
	time_, tick_, score_sep_, fg, number, row, col
import time

sep = 38
FPS = 30
width = 650;
height = 550
click_list = []
conn = sqlite3.connect('test.db')
cursor = conn.cursor()


def get(num, type):
	for i in range(num):
		w = next(type)
	return w


def MainGame(name, level, init_score=0):
	global row, col
	global click_list, total
	wash_wash = level_wash[level]
	total = get_total(row, col, 12)
	total_ = fake_copy(total)  # 一个膨胀的total
	start_pos, start, end = init_pos(row, col, width, height)  # 可以填入get_pos的第二个参数
	index = []
	tip_pos = []
	click = False  # 点击事件失效
	score = init_score
	score_sep = score_sep_  # 每一秒增加x分
	timer = 0
	time_sep = 1150
	choice = []
	tick = tick_  # 提示次数
	time = time_
	time_default = -time_sep * time  # 此处时时间的计算公式
	time_count = time_default
	stop = False
	fall_b = False
	default = True
	real_pos = (0, 0)
	size = 18
	pos__ = (18, 518)
	rankpos__ = (105, 518)
	checkable = True
	text = pygame.font.SysFont('Kaiti', size, True)
	text_tick = pygame.font.SysFont('Kaiti', 14, True)
	start__ = text.render('开始', True, (255, 255, 255))
	end__ = text.render('暂停', True, (255, 255, 255))
	## 排行榜
	rank__ = text.render('排行榜', True, (255, 255, 255))
	# print(total)
	while True:
		for event in pygame.event.get():
			if event.type == QUIT:
				pygame.display.quit()
			elif event.type == MOUSEBUTTONDOWN:
				if suc_b:
					init_score = score + (abs(time_count) // time_sep) * score_sep
					if level < 6:
						return name, init_score
					else:
						return name, init_score
				if fall_b:
					return name, score
				press_list = pygame.mouse.get_pressed()
				for i in range(len(press_list)):
					if press_list[i] == 0:
						real_pos = pygame.mouse.get_pos()
						click = True
		screen.blit(bg, (0, 0))
		screen.blit(button, (0, 508))
		suc_b = suc(total)
		if time_count > 0:
			fall_b = True

		if suc_b:
			screen.blit(success, (150, 100))
			stop = True
		if fall_b:
			screen.blit(false, (150, 100))
			stop = True
		if stop == True:  # 如果停止 ，停止贴图，
			screen.blit(start__, (pos__))
		else:  # 这个如果没有stop 那么就要贴图
			w = clock.get_rawtime()
			time_count += w
			timer -= w
			if timer < 0:
				timer = 0
			show_pic(screen, row, col, total, pic, start_pos)
			screen.blit(top, (0, 0))
			if time_count > time_default / 2:  # 时间进度条的划分
				color = (255, 0, 0)
			else:
				color = (0, 255, 0)
			pygame.draw.rect(screen, color, (410, 13, 200 * ((-time_count) / time_default), 20), 0)

			score_show = text.render(str(score), True, (255, 255, 255))  # 写下分数

			screen.blit(score_show, (510, 15))
			screen.blit(end__, pos__)
			screen.blit(rank__, rankpos__)
			if tip_pos:
				tip_pos_1 = start_pos[tip_pos[0]]
				tip_pos_2 = start_pos[tip_pos[1]]
				pygame.draw.rect(screen, (255, 0, 0), (tip_pos_1[0], tip_pos_1[1], sep, sep), 2)
				pygame.draw.rect(screen, (255, 0, 0), (tip_pos_2[0], tip_pos_2[1], sep, sep), 2)
		if choice and None not in choice:
			real = start_pos[choice[0]]
			pygame.draw.rect(screen, (255, 0, 0), (real[0], real[1], sep, sep), 2)
		# 点击开启点击时间  click_list
		if click:
			if not checkable:
				if level > 1:
					total = wash(total)
					total = wash_wash(total, number=row)
					total_ = fake_copy(total)
				else:
					total = wash(total)
					total_ = fake_copy(total)
			checkable = get_tip(total, total_)
			# print(real_pos)
			if not stop and real_pos:
				# 下面是对框架内的内容的删除
				if end[0] > real_pos[0] > start[0] and end[1] > real_pos[1] > start[1]:  # 此处为一个点击框架
					index = get_pos(real_pos, start_pos, sep)
					tip_pos.clear()  # 如果存在tip_pos 则消除
					# print(index)
					if index and index != None and not total[index[0]][index[1]] == '*':
						if click_list and click_list[0] != None and None not in [click_list]:
							w = click_list[0]
							check = tool(total, w[1], w[0], index[1], index[0])
							if is_same(total, click_list[0], index) and (check.main(total_)):
								total[click_list[0][0]][click_list[0][1]] = '*'
								total_[click_list[0][0] + 1][click_list[0][1] + 1] = '*'
								total[index[0]][index[1]] = '*'
								total_[index[0] + 1][index[1] + 1] = '*'
								score += 10
								# print(timer)
								if timer > time_sep:
									time_count -= time_sep * 3
								elif timer > 0:
									time_count -= time_sep * 2
								timer = time_sep * 2
								if level > 1:
									total = wash_wash(total, number=2)
									total_ = fake_copy(total)
							# print()
							# print('连接成功')
							# 	print(total)
							click_list.clear()
							choice.clear()
						else:
							click_list.clear()
							choice.clear()
							choice.append(index)
							click_list.append(index)
			click = False  # 不管如何结束点击时间
		screen.blit(text_tick.render(str(tick), True, (0, 0, 255)), (559, 525))
		# 下面添加暂停

		if real_pos:
			if real_pos[0] < 72 and real_pos[1] > 509:  # 暂停位置
				stop = stop ^ default
			if 170 > real_pos[0] > 95 and real_pos[1] > 509:  # 排行榜位置
				stop = stop ^ default
			if real_pos[0] < 73 and real_pos[1] < 32:  # 洗牌位置
				if level > 1:
					total = wash(total)
					total = wash_wash(total, number=row)
					total_ = fake_copy(total)
				else:
					total = wash(total)
					total_ = fake_copy(total)
				if tip_pos:
					tip_pos.clear()
			if real_pos[0] > 586 and real_pos[1] < 35:  # 退出
				return name, None  # 正式用  None,name
			if not stop and real_pos[0] > 588 and real_pos[1] > 517:  # 提示
				if tick > 0:
					tick -= 1
					tip_pos = get_tip(total, total_)
					if not tip_pos:
						tip_pos = []
						total = wash(total)
						total_ = fake_copy(total_)
		real_pos = None
		clock.tick()
		if not checkable:
			screen.blit(sorry, (150, 100))
		pygame.display.update()


def suc(total):
	for j in range(len(total)):
		for i in range(len(total[0])):
			if total[j][i] != '*':
				return False
	return True


# 这是一个选择关卡的辅助函数  调用后可以显示第x关
def level_show(font_pos, box_pos, active='', message='第一关', size=25):
	fontobject = pygame.font.SysFont('Kaiti', size, True)

	if active in message:
		color = (255, 0, 0)
	else:
		color = (0, 0, 255)
	pygame.draw.rect(screen, (0, 0, 0), box_pos, 1)

	pygame.draw.rect(screen, (255, 255, 255), box_pos, 1)
	text = fontobject.render(message, True, (color))
	screen.blit(text, font_pos)


# 这是显示关卡的主函数，调用后可以显示关卡和排名
def search(cursor):
	id = cursor.execute("select count(*) from users ").fetchone()[0] + 1
	c = cursor.execute('select * from users order by score desc ')
	return c.fetchall()[:5], id


# 这是显示关卡的主函数，调用后可以显示关卡和排名


def main(name):
	global screen, clock
	pygame.init()
	jiange = pygame.time.get_ticks()
	screen = pygame.display.set_mode((width, height))
	clock = pygame.time.Clock()
	pygame.display.set_caption('连连看')
	score = None
	while True:
		level = select(name, score=score)
		pygame.mixer_music.play(loops=-1)
		name, score = MainGame(name, level)


# 这是显示关卡的主函数，调用后可以显示关卡和排名
def select(name, score=None):
	# print(score,name)
	conn = sqlite3.connect('test.db')
	cursor = conn.cursor()
	sql = '''SELECT * FROM users WHERE name=:username '''
	c = cursor.execute(sql, {'username': name})
	if not score:
		pass
	else:
		info = c.fetchone()
		if not info:
			time_ = str(time.strftime("%m %d %X", time.localtime()))
			id = cursor.execute("select count(*) from users ").fetchone()[0] + 3
			sql = "INSERT INTO users VALUES (?,?,?,?,?)"
			cursor.execute(sql, (id, name, time_, 0, score))
		# print('insert')
		else:
			sql = "UPDATE users SET score=:score WHERE name=:name"
			cursor.execute(sql, {'score': score + info[4] + score, 'name': name})
		# print('update')
		conn.commit()

	text = pygame.font.SysFont('Kaiti', 20, True)
	text_g = pygame.font.SysFont('Kaiti', 30, True)
	text1 = pygame.font.SysFont('Kaiti', 15, True)
	sep = 60
	top_five_, id = search(cursor)
	five_id = []
	time_ = []
	top_five = []
	top_five_active = {}
	for i in top_five_:
		top_five.append(list(i))
		five_id.append(i[0])
		z = i[2].split(' ')
		print(z)
		time_.append('——' + z[0] + '月' + z[1] + '日' + z[2])  # 添加上时间
		top_five_active[i[0]] = nogood
	str_ = '第{}名:{:^4} 分数是{}'
	row = 100  # 设置列间距
	col = 150  # 设置行间距
	box_width = 100
	box_heigh = 25
	click = False
	active_s = cycle(['一', '二', '三', '四', '五', '六'])
	message_box = ['一', '二', '三', '四', '五', '六']
	active_ = next(active_s)
	col_num = 2  # 一列的数目
	while True:

		for event in pygame.event.get():
			if event.type == QUIT:
				pygame.display.quit()
			elif event.type == MOUSEBUTTONDOWN:
				if click:
					return number[active_]
				click = True
		active_ = '九'
		rel_x, rel_y = pygame.mouse.get_pos()
		screen.blit(fg, (0, 0))
		init_x = 80
		init_y = 130
		num_ = 1
		for i in message_box:
			if init_x - 10 < rel_x < init_x + box_width and init_y < rel_y < init_y + box_heigh:
				active_ = i
			level_show(font_pos=(init_x, init_y), box_pos=(init_x - 10, init_y, box_width, box_heigh), active=active_, message='第' + i + '关')

			init_x += col
			if num_ % col_num == 0:
				init_x = 80
				init_y += row
			num_ += 1
		screen.blit(text_g.render('请选择关卡', True, (0, 0, 0)), (100, 50))
		screen.blit(text_g.render('排行榜', True, (0, 0, 0)), (470, 50))
		index = 0
		for i in top_five:
			str__ = str_.format(index + 1, i[1], i[4])
			screen.blit(text.render(str__, True, (0, 0, 0)), (380, 120 + sep * index))

			# screen.blit(text1.render(str(time_[index]),True,(0,0,0)),(380,144+sep*index))
			# screen.blit(top_five_active[i[0]],(570,144+sep*index))
			index += 1
		pygame.display.update()


# 注册登陆界面
class MyApp(object):
	def __init__(self, parent):
		# 基本定义
		self.tip = False
		self.root = parent
		self.root.title("欢迎登陆连连看")
		self.canv = Tk.Canvas(self.root)
		# 图片位置
		self.img = Tk.PhotoImage(file='./picture/tkbg480.gif')
		self.img1 = Tk.PhotoImage(file='./picture/tkbg4801.gif')
		self.img_ = self.canv.create_image(0, 0, anchor='nw', image=self.img)
		self.canv.place(x=0, y=0, height=270, width=480)

		# 输入账号
		self.input_ = Tk.Variable()
		self.username = Tk.Entry(self.root, textvariable=self.input_, width=20, font=("Calibri", 17))
		self.username.place(x=150, y=75)
		# 输入密码
		self.input__ = Tk.Variable()
		self.password = Tk.Entry(self.root, textvariable=self.input__, width=20, font=("Calibri", 17), show='*')
		self.password.place(x=150, y=140)

		# 按钮
		btn1 = Tk.Button(self.root, bd=0, text="登陆", font=('楷体', 18), command=lambda: self.login(self.input_.get(), self.input__.get()))
		btn2 = Tk.Button(self.root, bd=0, text="注册", font=('楷体', 18), command=lambda: self.reg())
		btn3 = Tk.Button(self.root, bd=0, text="取消", font=('楷体', 18), command=lambda: self.exit())
		btn1.place(x=260, y=200)
		btn2.place(x=330, y=200)
		btn3.place(x=400, y=200)
		# 空的box
		self.box = Tk.Label(self.root, font=('Calibri', 17))
		self.box.place(x=0, y=0)

	# btn3.place(x=210,y=100)
	def hide(self):
		self.root.withdraw()

	# 点击登陆触发
	def login(self, user, pwd):
		sql = "SELECT * FROM user WHERE username=:username"
		real_user = cursor.execute(sql, {"username": user}).fetchone()
		if not real_user or real_user[2] != pwd:
			self.box['text'] = '您输入的账号或者密码错误'
			self.root.update()
		else:
			self.hide()
			main(user)

	# 点击创建账号触发
	def checkreg(self, user, pwd1, pwd2, frameName, message=''):
		frameName.destroy()
		if message:
			return self.close()
		sql = "SELECT * FROM user WHERE username=:user"
		real_user = cursor.execute(sql, {"user": user}).fetchone()
		if real_user or not pwd1 or not pwd2 or pwd1 != pwd2:
			return self.reg(tip=True)
		else:
			id = cursor.execute("select count(*) from user").fetchone()[0] + 1
			cursor.execute("INSERT INTO user VALUES (?,?,?)", (id, user, pwd1))
			conn.commit()
			return self.close()

	# 点击注册触发
	def reg(self, tip=None):
		self.box['text'] = ''
		self.hide()
		newframe = Tk.Toplevel()
		newframe.geometry("480x270-500+200")
		newframe.title = '注册账号'

		# 背景单个
		canv = Tk.Canvas(newframe)
		img_ = canv.create_image(0, 0, anchor='nw', image=self.img1)
		canv.place(x=0, y=0, height=270, width=480)

		# 取值列表
		username = Tk.Variable()
		password1 = Tk.Variable()
		password2 = Tk.Variable()

		# 实例列表
		user = Tk.Entry(newframe, textvariable=username, width=17, font=("Calibri", 17))
		pwd1 = Tk.Entry(newframe, textvariable=password1, width=17, show="*", font=("Calibri", 17))
		pwd2 = Tk.Entry(newframe, textvariable=password2, width=17, show='*', font=("Calibri", 17))
		btn1 = Tk.Button(newframe, bd=0, text='创建账号', font=('楷体', 18), command=lambda: self.checkreg(username.get(), password1.get(), password2.get(), newframe))
		btn2 = Tk.Button(newframe, text='返回', font=('Calibri', 15), command=lambda: self.checkreg(username.get(), password1.get(), password2.get(), newframe, '123'))
		# 贴 列表
		user.place(x=150, y=50)
		pwd1.place(x=150, y=100)
		pwd2.place(x=150, y=150)
		btn1.place(x=200, y=200)
		btn2.place(x=430, y=0)
		if tip:
			Tk.Label(newframe, text="您输入的账号存在或者密码不一致", font=("Calibri", 13)).place(x=150, y=185)

	def close(self):
		self.show()

	def show(self):
		self.root.update()
		self.root.deiconify()

	def exit(self):
		self.root.destroy()


if __name__ == '__main__':
	root = Tk.Tk()
	root.geometry("480x270-700+300")
	app = MyApp(root)
	root.mainloop()
